package com.zhang;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;

/**
 * spring整合mybatis 配置类
 */
@Configuration
@ComponentScan(basePackageClasses = MybatisConfig.class)
@MapperScan("com.zhang.mapper")
@EnableTransactionManagement
public class MybatisConfig {

    @Bean
    public DataSource dataSource(){
        DruidDataSource druid = new DruidDataSource();
        druid.setDriverClassName("com.mysql.jdbc.Driver");
        druid.setUrl("jdbc:mysql://localhost:3306/db_lovo?useSSl=false&characterEncoding=utf8&useUnicode=false&allowMultiQueries=true");
        druid.setUsername("root");
        druid.setPassword("123456");
        druid.setMaxActive(100);
        druid.setMinIdle(10);
        druid.setMaxWait(1000);
        return druid;
    }

    @Bean
    public SqlSessionFactoryBean factoryBean(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        return factoryBean;
    }

    @Bean
    public TransactionManager transactional(){
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(dataSource());
        return manager;
    }

}
